import type { Database } from 'sqlite3'
const path = require('path')
const electron = require('electron')
const sqlite3 = require('sqlite3').verbose()

let base: undefined | Database
let _cache = electron.app.getAppPath()
if (electron.app.isPackaged) {
  _cache = electron.app.getPath("exe")
  _cache = path.dirname(_cache)
}

function listenMain (local: Database) {
  electron.ipcMain.on('createTable', ((_, noteSql) => {
    console.log(noteSql)
    local.serialize(() => {
      local.run('create table if not exists student (id integer primary key autoincrement, name text, email text, phone integer);')
    })
  }))

  electron.ipcMain.on('selectQuery', ((_, noteSql) => {
    local.serialize(() => {
      local.all(noteSql, (err, rows) => {
        if (err === null) _.reply('findInState', noteSql, rows)
      })
    })
  }))

  electron.ipcMain.on('insertState', ((_, noteSql) => {
    local.serialize(() => {
      local.run(noteSql)
    })
  }))

  electron.ipcMain.on('updateState', ((_, noteSql) => {
    local.serialize(() => {
      console.log('updateState')
    })
  }))

  electron.ipcMain.on('deleteState', ((_, noteSql) => {
    local.serialize(() => {
      local.run(noteSql)
    })
  }))
}

export default function connectDB (name = 'learn.db') {
  return new Promise<Database>((resolve, reject) => {
    const file = path.resolve(_cache, name)

    if ((base as any)?.open) {
      resolve(base as Database)
    } else {
      base = new sqlite3.Database(file, (err: any) => {
        if (err) reject(err)
        console.log('The database connection is successful')
      }) as Database
      listenMain(base)
      resolve(base as Database)
    }
  })
}